'use strict';
import React, {
    Component
} from 'react'
import {
    Link,
    hashHistory
} from 'react-router'

import {
    HttpService,
    Tips,
    taskFinish,
    getLocalTime,
    AjaxUploadImgUrl,
    funcCheck
} from '../Tools'

import Header from './Common/Header'
import LoadingBox from './Common/LoadingBox'
import ConfirmBox from './Common/ConfirmBox'
import '../scss/news.scss'

import imgHead from '../Img/other/headerImgDefault.png'

export default class NewMsg extends React.Component {

    constructor(props) {
        super(props);
        this.page = 1
        this.pageSize = 10
        this.toBottom = 100
        this.dataLoad = 1
        this.state = {
            dataLoad: 1,
            dataEnd: 0,
            dataList: []
        }
    }
    componentWillUnmount() {
        clearInterval(sessionStorage.newsTimer)
    }
    componentWillMount() {
        this.getList()
        clearInterval(sessionStorage.newsTimer)
    }
    componentDidMount() {
        taskFinish('查阅班级通知', (status, config) => {
            if (status) {
                this.config = config;
                this.setState({
                    show: 1
                })
            }
        })
        //加载更多
        window.onscroll = () => {
            const {
                dataEnd,
                dataNull
            } = this.state;
            if (this.dataLoad == 1 || dataEnd == 1 || dataNull == 1)
                return;
            var scrollTop = 0;
            if (document.documentElement && document.documentElement.scrollTop) {
                scrollTop = document.documentElement.scrollTop;
            } else if (document.body) {
                scrollTop = document.body.scrollTop;
            }
            if (document.body.clientHeight - window.innerHeight - scrollTop <= this.toBottom) {
                this.page++;
                this.getList();
            }
        }

        //定时刷新
        if (this.props.quote == 'true') {
            sessionStorage.newsTimer = setInterval(() => {
                this.getList()
            }, 1000 * 60)
        }
    }

    //最新动态跳转
    DetailUrl(url) {
        if (url)
            hashHistory.push(url)
    }

    //忽略操作
    closeMsg(e) {
        let obj = e.currentTarget.children[0]
        const clsName = obj.className;
        if (document.querySelector('.newmsg i.show'))
            document.querySelector('.newmsg i.show').className = ''
        if (clsName == '') {
            obj.className = 'show'
        } else {
            obj.className = ''
        }
    }

    //获取数据
    getList() {
        if (!sessionStorage.ticket) {
            this.setState({
                dataLoad: 0,
                dataNull: 1
            })
            return
        }
        this.dataLoad = 1
        this.setState({
            dataLoad: 1
        })
        HttpService.query({
            url: '/jxt-commonbackground/ajaxSuiXun.do',
            //async: false,
            data: {
                jybTicket: sessionStorage.ticket,
                method: 'ajaxgetRecentNews',
                pageNo: this.page,
                pageSize: this.props.length ? this.props.length : this.pageSize
            },
            success: (res => {
                setTimeout(() => {
                    this.dataLoad = 0
                }, 600)
                if (res.code == 0) {
                    let dataEnd = 0
                    let dataNull = 0
                    let dataList = this.state.dataList.concat(res.rs);
                    if (res.rs.length == 0 || res.rs.length < (this.pageSize - 1)) {
                        dataEnd = 1
                        if (dataList.length == 0)
                            dataNull = 1
                    }
                    this.setState({
                        dataLoad: 0,
                        dataNull,
                        dataList,
                        dataEnd
                    })
                } else {
                    if (res == '未找到登录部门相关信息') {
                        funcCheck()
                        res = '当前帐号非任课教师<br/>部分功能无法使用'
                    }
                    Tips(res || res.msg);
                    this.setState({
                        dataLoad: 0,
                        dataNull: 1
                    })
                }
            }),
            fail: (msg) => {
                this.setState({
                    dataLoad: 0,
                    dataNull: 1
                })
            }
        })
    }

    //忽略请求
    closeMsgOk(id, index) {
        HttpService.query({
            url: '/jxt-commonbackground/ajaxSuiXun.do',
            data: {
                jybTicket: sessionStorage.ticket,
                method: 'ajaxMarkReaded',
                recentNewsid: id
            },
            success: (res => {
                if (res.code == 0) {
                    Tips('消息已忽略', 1)
                    //移除dataList
                    let newDataList = this.state.dataList
                    delete newDataList[index]
                    if (document.querySelectorAll('#scroll li').length < 2) {
                        this.refreshData()
                    } else {
                        this.setState({
                            dataList: newDataList
                        })
                    }
                } else {
                    Tips('操作错误')
                }
            })
        })
    }

    //刷新数据
    refreshData() {
        this.setState({
            dataLoad: 1,
            dataNull: 0,
            dataEnd: 0,
            dataList: []
        })
        this.page = 1
        this.getList()
    }

    render() {
        const {
            quote
        } = this.props
        const {
            dataLoad,
            dataNull,
            dataList
        } = this.state

        const dataTagList = dataList.map((item, index) => {
            if (this.props.length && index >= this.props.length)
                return
            let btn = null
            let url = null
            let haspic = false
            let title = '标题'
            let content = '内容'
            let detail = item.content
            let childtype = detail.childtype
            switch (item.businessType) {
                case '校内公告':
                    title = '公告标题'
                    content = '公告内容'
                    url = '/NtcDetail/' + item.businessId
                    detail.content = '点击进入详情查看>>'
                    // if (detail.requireSign == 1)
                    //     btn = '我已阅读'
                    break;
                case '家庭作业': //家庭作业
                    title = '作业标题'
                    content = '作业内容'
                    url = '/TaskDetail/' + item.businessId;
                    break;
                case '班级相册':
                    haspic = true
                    btn = '回复'
                    url = '/AlbumDetail/' + detail.dirId + '/' + detail.classid + '/' + encodeURIComponent(detail.dir) + '/' + encodeURIComponent(item.dirRemark || '暂无描述') + '/false/' + item.businessId
                    break;
                    // case '班级课表':
                    //     url = '/SubjectTimetable';
                    //     break;
                case '请假信息':
                    title = '请假类型'
                    content = '请假原因'
                    childtype = '请假批复通知' //sessionStorage.userrole == '班主任' ? '请假批复通知' : '请假提醒'
                    detail.title = detail.checkType1
                    detail.content = detail.content_p
                    detail.dateFrom = detail.dateFrom.replace(/\-/g, '.')
                    detail.dateTo = detail.dateTo.replace(/\-/g, '.')
                    switch (detail.checkType2) {
                        case '1':
                            detail.checkType2 = '同意'
                            break;
                        case '2':
                            detail.checkType2 = '不同意'
                            break;
                        default:
                            detail.checkType2 = '审批中'
                            break;
                    }
                    url = '/LeaveDetail/' + item.businessId + '/' + encodeURIComponent(detail.rolename) +
                        '/' + encodeURIComponent(detail.checkType1) + '/' + detail.dateFrom + '/' + detail.dateTo + '/' + encodeURIComponent(detail.checkType2) + '/' + encodeURIComponent(detail.content_p || '无') + '/' + encodeURIComponent(detail.content_t || '无');
                    break;
                case '成绩管理': //成绩管理
                    childtype = '成绩发布通知'
                    title = '考试名称'
                    content = '考试类型'
                    detail.content = detail.testType
                    let isKT = detail.testType == '统考成绩' ? true : false
                    url = '/ScoreDetail/' + item.businessId + '/' + isKT;
                    break;
                case '成长记录':
                    btn = '回复'
                    haspic = true
                    childtype = '评论提醒'
                    url = '/GrowthRecordDetails/' + item.businessId + '/true';
                    break;
                case '班级通知':
                    break;
                default:
                    url = '/';
                    Tips('获取数据异常')
                    break;
            }

            return (
                <li>
                    <div className='type'>
                        <title className={sessionStorage.userrole=='家长'?'':'jscolor'}>{childtype}</title>
                        <time>{getLocalTime(item.crateTime.replace(/\-/g,'/'))}</time>
                        <a onClick={this.closeMsg.bind(this)} ><i onClick={this.closeMsgOk.bind(this,item.id,index)}></i></a>
                    </div>
                    <div className={haspic?'content haspic':'content'} onClick={this.DetailUrl.bind(this,url)}>
                        {/*<span className='datail'>详情</span>*/}
                        {/*btn?<span className='btnlink'>{btn}</span>:''*/}
                        {!haspic?
                        <div>
                            {detail.title?<div className='text-els'>{title}：{detail.title}</div>:null}
                            {detail.dateFrom?<div className='text-els2'>请假时间：{detail.dateFrom + '-' + detail.dateTo}</div>:''}
                            <div className='text-els2' style={{display:detail.title?null:'block'}}>{content}：{detail.content}</div>
                            {detail.checkType2?<div className='text-els2'>审批状态：{detail.checkType2}</div>:''}
                            {detail.content_t?<div className='text-els2'>老师回复：{detail.content_t}</div>:''}
                            {detail.needFinishTime?<div className='text-els2'>完成时间：{detail.needFinishTime}</div>:''}
                            {detail.score?<div className='text-els2'>考试分数：{detail.score}</div>:''}
                        </div>:
                        <div>
                            <img className='imghead' src={imgHead} />
                            <div className='username'><span>{detail.username||detail.photoUserName}</span>{childtype=='点赞提醒'?'赞了你的照片':''}</div>
                            {childtype=='评论提醒'?
                                <div className='comment'>{detail.comment||detail.photoComment}</div>:''
                            }
                            <div className='piccontent' style={{minHeight:detail.fileId?'60px':'none'}}>
                                {detail.fileId?<div className='photo' style={{backgroundImage:'url('+AjaxUploadImgUrl+detail.fileId.split(',')[0]+')'}}></div>:''}
                                <div className='text-els2'>{detail.photoContent||detail.fileRemark}</div>
                            </div>
                        </div>}
                    </div>
                </li>
            )
        })

        let newsStyle = ''
        return (
            <div >
                <div className='newmsg' id='newmsg'>
                    {quote?'':<Header title='最新动态' link={<a className='h_link refresh' onClick={this.refreshData.bind(this)}></a>} />}
                    <ul className='list listnew' id='scroll'>
                        {dataTagList}
                    </ul>
                    <div style={{background:'#eee'}}>
                        <LoadingBox dataLoad={dataLoad} />
                    </div>
                    {
                        dataTagList!=''?
                        <div>
                            {
                            quote?
                            <div className={sessionStorage.userrole=='家长'?'morelink':'morelink jscolor'} onClick={this.DetailUrl.bind(this,'/news')}>更多动态信息>></div>
                            :''
                            }
                        </div>
                        :''}
                        {
                            dataNull==1?
                        <div className={sessionStorage.userrole=='家长'?'newstip':'newstip newstipjs'}>
                            <p className={sessionStorage.userrole=='家长'?'hy':'hy jscolor'}>欢迎使用随寻通</p>
                            <p className='zw'>暂无最新动态</p>
                        </div>:''}
                </div>
                <ConfirmBox config={this.config} show={this.state.show} sigle='1'/>
            </div>
        )
    }
}
